import React from 'react';
import styles from './index.less';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Goods } from '@/types/business';
import { request } from '@umijs/max';
import { Button, Modal, Switch } from 'antd';
import { history } from '@umijs/max';

export default function Page() {

  const ref = React.useRef<ActionType>();

  /**
   * 删除商品
   */
  const handleDelete = (entity: Goods) => {
    // 二次弹窗确认
    Modal.confirm({
      title: '删除商品',
      content: '确定删除该商品吗？',
      onOk: () => {
        // 删除商品
        request(`/admin/goods/deleteGoods?id=${entity.id}`, {
          method: 'post',
        }).then(res => {
          if (res.data) {
            ref.current?.reload();
          }
        });
      },
    });
  };

  const columns: ProColumns<Goods>[] = [
    {
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
    },
    {
      dataIndex: 'name',
      title: '商品名称',
    },
    {
      dataIndex: 'size',
      title: '规格',
      hideInSearch: true
    },
    {
      dataIndex: 'price',
      title: '价格',
      hideInSearch: true,
    },
    {
      dataIndex: 'originPrice',
      title: '原价',
      hideInSearch: true,
    },
    {
      dataIndex: 'enable',
      title: '是否上架',
      valueEnum: {
        'TRUE': { text: '上架', status: 'Default' },
        'FALSE': { text: '下架', status: 'Default' },
      },
      render: (dom, entity) => {
        return <Switch value={entity.enable === 'TRUE'} onChange={(values) => {
          request(`admin/goods/enableGoods?id=${entity.id}&enable=${values ? 1 : 0}`, {
            method: 'post',
          }).then(res => {
            if (res.data) {
              ref.current?.reload();
            }
          });
        }}></Switch>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (dom, entity) => [
        <a key="edit" onClick={() => history.push(`/goods/saveOrUpdate?id=${entity.id}&type=edit`)}>编辑</a>,
        <a key="delete" onClick={() => handleDelete(entity)}>删除</a>,
      ],
    },
  ];

  return (
    <div>
      <PageContainer title="商品管理">
        <ProTable
          actionRef={ref}
          columns={columns}
          rowKey="id"
          request={async (params) => {
            const data = await request('/admin/goods/page', {
              data: { ...params, queryCondition: params },
              method: 'post',
            });
            return {
              data: data.data.records,
              success: true,
              total: data.data.total,
            };
          }}
          toolBarRender={() => [
            <Button type={'primary'} key={'add-good'} onClick={() => history.push(`/goods/saveOrUpdate?type=add`)}>新增</Button>,
          ]}
        ></ProTable>
      </PageContainer>
    </div>
  );
}
